package org.huzhp.console.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.shiro.SecurityUtils;
import org.huzhp.console.core.RouteUtil;
import org.huzhp.console.entity.vo.GatewayRouteVo;
import org.huzhp.console.service.IConsoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Description: 首页
 * @Author: huzp
 * @CreateDate: 2020/3/14 13:03
 * @Version: 1.0
 */
@Controller
public class IndexController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${eureka.client.serviceUrl.defaultZone}")
    private String eurekaServer;
    @Value("${spring.cloud.gateway.server}")
    private String gatewayServer;

    @Autowired
    private IConsoleService consoleService;


    @GetMapping(value = {"/", "index"})
    public String index(Map map) {
        map.put("user", SecurityUtils.getSubject().getPrincipal());
        return "index";
    }

    @GetMapping("welcome")
    public String welcome() {
        return "welcome";
    }

    @GetMapping("app/list")
    public String app() {
        return "app/app_list";
    }

    @GetMapping("gateway/form")
    public String gatewayForm(String routeId, String resourceId, Map map) throws JsonProcessingException {
        GatewayRouteVo route = consoleService.findRouteByRouteId(routeId);
        map.put("route", route != null ? route : RouteUtil.buildGatewayRoute(routeId));
        return "gateway/form";
    }

    @GetMapping("gateway/monitor")
    public String gatewayMonitor() throws JsonProcessingException {
        return "gateway/monitor";
    }

    @GetMapping("gateway/log")
    public String gatewayLog() throws JsonProcessingException {
        return "gateway/log";
    }

    @GetMapping("eureka/status")
    @ResponseBody
    public Map eurekaStatus() {
        return restTemplate.getForObject(eurekaServer + "/myeureka/status", Map.class);
    }

    @GetMapping("eureka/apps")
    @ResponseBody
    public Object eurekaApps() {
        Map result = restTemplate.getForObject(eurekaServer + "/eureka/apps", Map.class);
        return ((Map) result.get("applications")).get("application");
    }

    @GetMapping("gateway/status")
    @ResponseBody
    public Map gatewayStatus() {
        return restTemplate.getForObject(gatewayServer + "/gateway/status", Map.class);
    }

}
